package net;

public class Test2 {
    public static void main(String[] args) {
        B.quick();
        B.mergeTest();

    }
}

class B{
    public static void quick(){
        int arr[] = new int[4000000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 10000000);
        }
        long s1 = System.currentTimeMillis();
        A.quickSort(arr, 0, arr.length - 1);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);
    }

    public static void mergeTest(){
        int arr[] = new int[4000000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 10000000);
        }
        long s1 = System.currentTimeMillis();
        A.mergeSort(arr, 0, arr.length - 1);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);
    }
}

class A{
    public static void quickSort(int[]arr,int left,int right){
        if(left>=right){
            return;
        }
        int piv=parition(arr,left,right);
        quickSort(arr,left,piv-1);
        quickSort(arr,piv+1,right);
    }
    public static int parition(int[]arr,int start,int end) {
        int i = start;
        int pivot = arr[start];
        while (start < end) {
            while (start < end && arr[end] >= pivot) {
                end--;
            }
            while (start < end && arr[start] <= pivot)
                start++;
            swap(arr, start, end);

        }
        swap(arr, start, i);
        return start;
    }

    public static void swap(int[]arr,int i,int j){
        int tem=arr[i];
        arr[i]=arr[j];
        arr[j]=tem;
    }

    public static  void mergeSort(int[]arr,int left,int right){
        if(left==right){
            return;
        }
        int mid=(left+right)/2;
        mergeSort(arr,left,mid);
        mergeSort(arr,mid+1,right);

        merge(arr,left,right,mid);
    }

    public static void merge(int[]arr,int left,int right,int mid){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;

        int k=0;
        int temarr[]=new int[right-left+1];

        while(s1<e1&&e2<s2){
            if(arr[s1]<=arr[s2]){
                temarr[k++]=arr[s1++];
            }
            else {
                temarr[k++]=arr[s2++];
            }
        }
        while(s1<e1){
            temarr[k++]=arr[s1++];
        }
        while(s2<e2){
            temarr[k++]=arr[s2++];
        }
        for(int i=0;i<temarr.length;i++){
            arr[left+i]=temarr[i];
        }
    }
}
